package com.skwyb.form.utils;

import com.skwyb.form.constants.ResultCode;
import com.skwyb.form.core.BusinessException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

@Log4j2
public class AssertUtils {

    public static void isTrue(boolean flag, ResultCode codeEnum) {
        isTrue(flag, codeEnum.getCode(), codeEnum.getMessage());
    }

    public static void isTrue(boolean flag, String message) {
        isTrue(flag, ResultCode.PARAM_ILLEGAL.getCode(), message);
    }

    private static void isTrue(boolean flag, int code, String message) {
        if (!flag) {
            throw new BusinessException(code, message);
        }
    }

    public static void isFalse(boolean flag, ResultCode codeEnum) {
        isTrue(!flag, codeEnum.getCode(), codeEnum.getMessage());
    }

    public static void isFalse(boolean flag, String message) {
        isTrue(!flag, message);
    }

    public static void isNull(Object obj, String message) throws BusinessException {
        if (null == obj) {
            throw new BusinessException(ResultCode.PARAM_NULL);
        }
        if (StringUtils.isBlank(obj.toString())) {
            throw new BusinessException(ResultCode.PARAM_NULL);
        }
    }

    public static void equals(String str, String... equal) throws BusinessException {
        if (StringUtils.isBlank(str)) {
            return;
        }
        equalsAndMsg(str, "the param[" + str + "] is illegal", equal);
    }

    public static void equalsAndMsg(String str, String message, String... equal) throws BusinessException {
        if (StringUtils.isBlank(str)) {
            return;
        }
        boolean flag = true;
        for (String k : equal) {
            if (k.equals(str)) {
                flag = false;
                break;
            }
        }
        if (flag) {
            throw new BusinessException(ResultCode.PARAM_NOT_EQUALS);
        }
    }

    public static String urlEncode(String url) {
        if (StringUtils.isBlank(url)) {
            return StringUtils.EMPTY;
        }
        try {
            return URLEncoder.encode(url, String.valueOf(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException e) {
            log.error("URLEncoder error", e);
        }
        return StringUtils.EMPTY;
    }
}
